﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

namespace PolicyInjectionExtension
{
    public static class PolicyInjectionHelperFactory
    {
        private static volatile PolicyInjectionHelper defaultHelper;
        private static readonly object singletonLock = new object();

        #region Default Helper
        public static PolicyInjectionHelper Helper
        {
            get
            {
                if (defaultHelper == null)
                {
                    lock (singletonLock)
                    {
                        if (defaultHelper == null)
                        {
                            defaultHelper = GetHelperFromConfigure(null) ;
                        }
                    }
                }
                return defaultHelper;
            }
            private set
            {
                lock (singletonLock)
                {
                    defaultHelper = value;
                }
            }
        }
        #endregion

        #region GetHelper
        public static PolicyInjectionHelper GetHelperFromPolicies(List<PolicyDataExtension> policies)
        {
            return new CodePolicyInjectionHelper (policies);
        }

        public static PolicyInjectionHelper GetHelperFromConfigure(IConfigurationSource configurationSource)
        { 
            return new ConfigurationPolicyInjectionHelper(configurationSource);
        }
        #endregion

        #region SetHelper
        /// <summary>
        /// if configurationSource is null,
        /// using ConfigurationSourceFactory.Create() to get default configuration source
        /// </summary>
        /// <param name="configurationSource"></param>
        public static void SetupConfigureHelper(IConfigurationSource configurationSource)
        {
            if (configurationSource == null)
                configurationSource = ConfigurationSourceFactory.Create();
            Helper = GetHelperFromConfigure(configurationSource);
        }

        /// <summary>
        /// if  policies is null
        /// using new policy list to replace null 
        /// </summary>
        /// <param name="policies"></param>
        public static void SetupPoliciesHelper(List<PolicyDataExtension> policies)
        {
            if (policies == null)
                policies = new List<PolicyDataExtension>();
            Helper = GetHelperFromPolicies(policies);
        }
 
        #endregion
    }
}
